package xyz.lwm.lazycat.mybatisflex;

import org.apache.ibatis.transaction.Transaction;
import xyz.lwm.lazycat.transaction.execute.TransactionManager;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;

/**
 * mybatis transaction
 *
 * @author lwm
 */
public class LazycatTransaction implements Transaction {

    private final DataSource dataSource;

    private Connection connection;

    private boolean isTransactionOpen;

    private boolean isAutoCommit;

    public LazycatTransaction(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Override
    public Connection getConnection() throws SQLException {
        if (connection == null) {
            connection = dataSource.getConnection();
            isTransactionOpen = TransactionManager.current().isOpen();
            isAutoCommit = connection.getAutoCommit();
        }
        return connection;
    }

    @Override
    public void commit() throws SQLException {
        if (connection != null && !isTransactionOpen && !isAutoCommit) {
            connection.commit();
        }
    }

    @Override
    public void rollback() throws SQLException {
        if (connection != null && !isTransactionOpen && !isAutoCommit) {
            connection.rollback();
        }
    }

    @Override
    public void close() throws SQLException {
        if (connection != null && !isTransactionOpen) {
            connection.close();
        }
    }

    @Override
    public Integer getTimeout() throws SQLException {
        if (connection != null) {
            try {
                return connection.getNetworkTimeout();
            } catch (SQLFeatureNotSupportedException e) {
                //
            }
        }
        return null;
    }

}
